<script>
import { v4 } from "uuid";
import { MQTT_IP, MQTT_OPTIONS } from "@/utils/mqtt.js";
const mqtt = require("mqtt/dist/mqtt.js");
let client;
export default {
    data() {
        return {};
    },
    onLaunch: function () {
        const that = this;
        uni.getSystemInfo({
            success: function (e) {
                let navHeight = e.statusBarHeight;
                // #ifndef MP
                if (e.platform === "android") {
                    navHeight = e.statusBarHeight + 50;
                } else {
                    navHeight = e.statusBarHeight + 45;
                }
                // #endif

                // #ifdef MP-WEIXIN

                // 获取胶囊按钮的布局位置信息，坐标信息以屏幕左上角为原点
                const custom = wx.getMenuButtonBoundingClientRect();

                // 导航栏高度 = 状态栏到胶囊的间距（胶囊距上距离-状态栏高度） * 2 + 胶囊高度 + 状态栏高度。

                navHeight =
                    custom.height +
                    (custom.top - e.statusBarHeight) * 2 +
                    e.statusBarHeight;
                const navTop = custom.top;
                const capsuleHeight = custom.height;
                // #endif

                // #ifdef MP-ALIPAY
                navHeight = e.statusBarHeight + e.titleBarHeight;
                // #endif
                uni.setStorageSync("navHeight", navHeight);
                // #ifdef MP-WEIXIN
                uni.setStorageSync("navTop", navTop);
                uni.setStorageSync("capsuleHeight", capsuleHeight);
                // #endif
            },
        });
    },
    onShow: function () {},
    mounted() {
        const userInfo = uni.getStorageSync("user_info");
        if (userInfo) {
            this.connect(userInfo.user.userId);
        }
    },
    onHide: function () {},
    methods: {
        connect(userId) {
            const self = this;
            MQTT_OPTIONS.clientId = v4();
            // MQTT_OPTIONS.clientId = plus.push.getClientInfo().clientid;
            const that = this;
            // client = mqtt.connect('wxs://' + MQTT_IP, MQTT_OPTIONS)
            // #ifdef H5
            client = mqtt.connect("ws://" + MQTT_IP, MQTT_OPTIONS);
            // #endif
            //app的连接是 'wx://' + url。
            //#ifdef MP-WEIXIN||APP-PLUS
            client = mqtt.connect("wx://" + MQTT_IP, MQTT_OPTIONS);
            // #endif

            client
                .on("connect", function () {
                    console.log("连接成功");
                    // 订阅
                    let topTic = `/message/user/${userId}/#`;
                    client.subscribe(topTic, function (err) {
                        if (!err) {
                            // client.publish('test')
                            console.log("订阅成功");
                        }
                    });
                })
                .on("reconnect", function (error) {
                    console.log("正在重连...", error);
                })
                .on("error", function (error) {
                    console.log("连接失败...", error);
                })
                .on("end", function () {
                    console.log("连接断开");
                })
                .on("message", function (topic, message) {
                    console.log("接收推送信息：", message.toString());
                    // plus.push.createMessage("您有新消息","",{
                    // 			title:"xxx"
                    // 		})
                    // self.pushMessage(message)
                });
        },
        pushMessage(msg) {
            console.log(msg, "msg");
            //#ifdef APP-PLUS
            const _handlePush = function (message) {
                /**
                 * 通过 vuex 来同步页面的数据，仅做演示。
                 * 实际开发中，这里可能是跳转到某个页面等操作，请根据自身业务需求编写。
                 */
                uni.switchTab({
                    url: "pages/tabBar/news/index",
                });
            };
            plus.push.addEventListener("click", (msg) => {
                _handlePush(msg);
            });
            plus.push.addEventListener("receive", (msg) => {
                console.log("msg", msg);
                const options = {
                    cover: false,
                };
                plus.push.createMessage(msg.payload, "LocalMSG", options);
            });
            // #endif
            // plus.push.addEventListener('click', function(msg) {
            // 	// console.log("click", msg);
            // 	//处理点击消息的业务逻辑代码
            // 	plus.nativeUI.alert("click:" + JSON.stringify(msg));
            // 	plus.nativeUI.alert(msg.payload);
            // }, false);
            // //监听接收透传消息事件
            // plus.push.addEventListener('receive', function(msg) {
            // 	//处理透传消息的业务逻辑代码
            // 	// console.log("receive",msg)
            // 	plus.nativeUI.alert("recevice:" + JSON.stringify(msg))
            // }, false);
        },
    },
};
</script>

<style>
@import "@/static/css/basic.css";
@import "@/static/css/reset.css";
/* 解决头条小程序组件内引入字体不生效的问题 */
/* #ifdef MP-TOUTIAO */

@font-face {
    font-family: uniicons;
    src: url("/static/uni.ttf");
}

/* #endif */
</style>
